package com.beyond.theme

import android.app.Activity
import android.app.WallpaperManager
import android.os.Build
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import com.beyond.common.dp.theme.DarkModePreference
import com.beyond.common.dp.theme.ThemeNamePreference
import com.beyond.common.ext.toColorOrNull
import com.beyond.common.local.LocalCustomPrimaryColor
import com.beyond.common.local.LocalThemeName
import com.beyond.common.util.LogUtils
import com.kyant.monet.LocalTonalPalettes
import com.kyant.monet.PaletteStyle
import com.kyant.monet.TonalPalettes
import com.kyant.monet.TonalPalettes.Companion.toTonalPalettes
import com.kyant.monet.dynamicColorScheme

/**
 * @author chen
 * @time 2023/5/31 10:42
 * @name Theme.kt
 * @class describe
 */

// https://developer.android.google.cn/codelabs/jetpack-compose-theming?hl=zh-cn#0
//    primary: Color, // 应用程序主要颜色
//    primaryVariant: Color, // 主要变体颜色，用于区分使用主题颜色的应用程序的两个                            //元素，例如顶部应用程序栏和系统状态栏
//    secondary: Color, // 辅助颜色
//    secondaryVariant: Color, // 辅助变体颜色，用于区分使用辅助颜色的应用程序的两                              //个元素
//    background: Color, // 背景颜色
//    surface: Color, // 表面颜色，用于组件的表面
//    error: Color, // 错误颜色，如指示组件（如文本字段）中的错误
//    onPrimary: Color, // 用于显示在原色顶部的文本和图标的颜色
//    onSecondary: Color, // 用于显示在辅助颜色顶部的文本和图标的颜色
//    onBackground: Color, // 用于显示在背景颜色顶部的文本和图标的颜色
//    onSurface: Color, // 用于显示在表面颜色顶部的文本和图标的颜色
//    onError: Color, // 用于显示在错误颜色顶部的文本和图标的颜色
//    isLight: Boolean // 是否为浅色模式

@Composable
fun ProjectManageTheme(
    darkThemeInt: Int,
    systemScheme: Boolean,
    content: @Composable () -> Unit
) {
    val darkTheme  =DarkModePreference.isInDark(darkThemeInt)
    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as Activity).window
            SystemUiController(window).setSystemBarsColor(
                color = Color.Transparent,
                darkIcons = !darkTheme
            )
        }
    }
    val wallpaperPalettes: Map<String, TonalPalettes> = extractAllTonalPalettes()
    val tonalPalettes = wallpaperPalettes.getOrElse(LocalThemeName.current) {
        ThemeNamePreference.values[0].keyColor.toTonalPalettes(style = PaletteStyle.Content)
    }
    val context = LocalContext.current

    // LocalTonalPalettes 直接更新颜色
    CompositionLocalProvider(
        LocalTonalPalettes provides tonalPalettes,
    ) {
        val colorScheme = if (systemScheme) {
            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
        } else {
            dynamicColorScheme(isLight = !darkTheme)
        }
        MaterialTheme(
            colorScheme = colorScheme,
            typography = Typography,
            content = content
        )
    }
}


@Composable
fun extractAllTonalPalettes(): Map<String, TonalPalettes> {
    return extractTonalPalettesFromWallpaper() + extractTonalPalettes()
}

@Composable
fun extractTonalPalettes(): Map<String, TonalPalettes> {
    val cc = LocalCustomPrimaryColor.current
    return ThemeNamePreference.values.associate { it.name to it.keyColor.toTonalPalettes(style = PaletteStyle.Content) }
        .toMutableMap().also { map ->
            val customPrimaryColor =
                cc.toColorOrNull() ?: Color.Transparent
            map[ThemeNamePreference.CUSTOM_THEME_NAME] = customPrimaryColor.toTonalPalettes(style = PaletteStyle.Content)
        }
}

@Composable
fun extractTonalPalettesFromWallpaper(): Map<String, TonalPalettes> {
    val context = LocalContext.current
    val preset = mutableMapOf<String, TonalPalettes>()

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1 && !LocalView.current.isInEditMode) {
        val colors = WallpaperManager.getInstance(context)
            .getWallpaperColors(WallpaperManager.FLAG_SYSTEM)
        val primary = colors?.primaryColor?.toArgb()
        val secondary = colors?.secondaryColor?.toArgb()
        val tertiary = colors?.tertiaryColor?.toArgb()
        if (primary != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                preset["WallpaperPrimary"] = context.getSystemTonalPalettes()
            } else {
                preset["WallpaperPrimary"] = (Color(primary).toTonalPalettes(style = PaletteStyle.Content))
            }
        }
        if (secondary != null) preset["WallpaperSecondary"] = Color(secondary).toTonalPalettes(style = PaletteStyle.Content)
        if (tertiary != null) preset["WallpaperTertiary"] = Color(tertiary).toTonalPalettes(style = PaletteStyle.Content)
    }
    return preset
}